package cn.yi.medicalsys.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;

import cn.yi.medicalsys.pojo.Doctor;
import cn.yi.medicalsys.pojo.Office;
import cn.yi.medicalsys.service.DoctorService;
import cn.yi.medicalsys.service.OfficeService;
import cn.yi.medicalsys.service.impl.DoctorServiceImpl;
import cn.yi.medicalsys.service.impl.OfficeServiceImpl;
import cn.yi.medicalsys.utils.StringUtils;

public class DoctorServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	// 修改
	public void modify(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		DoctorService doctor = new DoctorServiceImpl();
		String docdid = request.getParameter("docdid");// 医生姓名
		String doctAge = request.getParameter("docage");
		String appellation = request.getParameter("docappellation");
		String doctPhone = request.getParameter("docPhone");
		String doctEmail = request.getParameter("docEmail");
		System.out.println("doctAge:" + doctAge);
		Integer age = null;
		if (doctAge != null && !doctAge.equals("")) {
			age = Integer.valueOf(doctAge);
		} else {
			age = -1;
		}
		String docoffice = request.getParameter("docoffice");
		String newdocoffice = docoffice.substring(docoffice.indexOf("-") + 1)
				.intern();
		Integer officeid = null;
		if (newdocoffice != null && !newdocoffice.equals("")) {
			officeid = Integer.valueOf(newdocoffice);
		} else {
			officeid = -1;
		}
		boolean flag = doctor.updateDoctor(age, appellation, doctPhone,
				doctEmail, Integer.valueOf(docdid), officeid);
		if (flag) {
			out.print("<script>alert('修改成功');history.back()</script>");
		} else {
			out.print("<script>alert('修改失败');history.back()</script>");
		}
	}

	// 添加 以及上传图片
	public void addDoctor(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		// 1.判断是否为二进制流的提交方式
		DoctorService doctor = new DoctorServiceImpl();
		Doctor docto = new Doctor();
		// 读取远程服务器路径 separator分隔符
		String uploadPath = request.getServletContext().getRealPath("/")
				+ File.separator + "upload";
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) { // 如果不存在此文件夹
			uploadDir.mkdirs();// 则创建
		}
		boolean isOk = false;// 判断图片格式
		boolean isOnlyText = false;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			out.print("1");
			// 2.创建文件上传所需要的 API实列
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 3.解析request 请求，获取FileItem对象集合
			List<FileItem> list = upload.parseRequest(request);
			// 4.循环遍历集合中的数据
			for (FileItem item : list) {// 从表中一行一行读取
				// 判断是否为普通表单 是则返回true
				if (item.isFormField()) {
					// 普通表单
					String fileldName = item.getFieldName();
					if ("hospitalno".equals(fileldName)) {
						docto.sethId(Integer.valueOf(item.getString("utf-8")));// 读取内容并设置格式
					} else if ("adninno".equals(fileldName)) {
						docto.setoId(Integer.valueOf(item.getString("utf-8")));
					} else if ("name".equals(fileldName)) {
						docto.setDoctName(item.getString("utf-8"));
					} else if ("sex".equals(fileldName)) {
						docto.setDoctSex(item.getString("utf-8"));
					} else if ("age".equals(fileldName)) {
						docto.setDoctAge(Integer.valueOf(item
								.getString("utf-8")));
					} else if ("phone".equals(fileldName)) {
						docto.setDoctPhone(item.getString("utf-8"));
					} else if ("appellation".equals(fileldName)) {
						docto.setAppellation(item.getString("utf-8"));
					} else if ("email".equals(fileldName)) {
						docto.setDoctEmail(item.getString("utf-8"));
					} else if ("brief".equals(fileldName)) {
						docto.setDoctIntr(item.getString("utf-8"));
					}
				} else {
					String name = new String(item.getName().getBytes(), "utf-8");
					if (name != null && !name.equals("")) {
						// 判断纯汉字 须在后面添加字母 方可不会出错
						String regex = "[a-zA-Z]";
						String charName = name.substring(
								name.lastIndexOf(".") - 1,
								name.lastIndexOf("."));
						if (!charName.matches(regex)) {
							name = name.substring(0, name.lastIndexOf(".") - 1)
									+ "kgc"
									+ name.substring(name.lastIndexOf("."));
						}
					}
					if (name != null && !name.equals("")) {
						if (!StringUtils.checkImg(name)) {
							out.print("<script>alert('图片类型加载出错');history.back()</script>");
						} else {
							String strNew = StringUtils.getNewName(name);
							docto.setDoctImage(strNew);
							File file = new File(uploadPath, strNew);// comcat/load
							item.write(file);
							isOk = true;
						}
					} else {
						isOnlyText = true;
					}
				}
			}
		} else {
			out.print("0");
		}
		// 调用业务逻辑层
		if (isOk || isOnlyText) {
			boolean result = doctor.addDoctor(docto);
			if (result) {
				out.print("<script>alert('添加成功');</script>");
				response.sendRedirect("staff.jsp");
			} else {
				out.print("<script>alert('添加失败');history.back()</script>");
			}
		}
	}

	// 删除医生
	public void delDoctor(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		DoctorService doctor = new DoctorServiceImpl();
		String nid = request.getParameter("nid");
		Integer did = null;
		if (nid != null && !nid.equals("")) {
			did = Integer.valueOf(nid);
		}
		boolean flag = doctor.deleteDoctor(did);
		if (flag) {
			out.print("<script>alert('恭喜你，删除成功');</script>");
			response.sendRedirect("staff.jsp");
		} else {
			out.print("<script>alert('删除失败');history.back()</script>");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();		
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null && !action.equals("")) {
			if (action.equals("modify")) {
				this.modify(request, response);
			} else if (action.equals("add")) {
				try {
					this.addDoctor(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (action.equals("del")) {
				this.delDoctor(request, response);
			} else {
				out.print("<script>alert('action 传值有误');history.back()</script>");
			}
		} else {
			DoctorService doctor = new DoctorServiceImpl();
			OfficeService office = new OfficeServiceImpl();
			String id = request.getParameter("id");
			Doctor doc = doctor.findDoctorByNo(Integer.valueOf(id));
			Office off = office.findOfficeByNo(doc.getoId());
			String jsondoc = JSON.toJSONString(doc);
			out.print(jsondoc);
			// session.setAttribute("doc", doc);
			// session.setAttribute("off", off);
			// response.sendRedirect("staff.jsp");
		}
		out.flush();
		out.close();
	}

	public void init() throws ServletException {
	}

}
